import { CommonParams } from './types'
import { ref } from 'vue'
import { AxiosResponse } from 'axios'

import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

interface ResBody extends AxiosResponse {
  list: object[]
  total: number
}

type ParamsType = {
  pageSize?: number
  needLoadMore?: boolean
  data: CommonParams
}

const useList = (
  listReq: any,
  params: ParamsType = {
    pageSize: 10,
    needLoadMore: true,
    data: {}
  }
) => {
  const { pageSize, needLoadMore, data } = params
  const list = ref()
  const pageInfo = ref({
    pageNum: 1,
    pageSize,
    total: 0
  })
  const keyWord = ref('')

  const getList = () => {
    if (!listReq) {
      return console.error('请传入获取列表的接口')
    }
    const params = {
      ...pageInfo.value,
      ...data,
      keyWord: keyWord.value
    }
    return listReq(params).then((res: ResBody) => {
      if (pageInfo.value.pageNum === 1) {
        list.value = res.data.list
      } else {
        list.value = [...list.value, ...res.data.list]
      }
      pageInfo.value.total = res.data.total || 0
    })
  }

  const initList = () => {
    pageInfo.value.pageNum = 1
    keyWord.value = ''
    return getList()
  }

  const handleLoadMore = () => {
    pageInfo.value.pageNum += 1
    return getList().then(() => {
      if (!list.value.length) {
        uni.showToast({
          title: '没有更多了',
          icon: 'none'
        })
      }
    })
  }
  onPullDownRefresh(() => {
    initList().then(uni.stopPullDownRefresh)
  })

  if (needLoadMore) {
    onReachBottom(handleLoadMore)
  }

  getList()

  return {
    list,
    pageInfo,
    keyWord,
    getList,
    initList,
    handleLoadMore
  }
}

export default useList
